package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.PageResult;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageResult<DishDto> findPage(Long page, Long pageSize, String name){
        Page myPage = new Page(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishMapper.selectPage(myPage,queryWrapper);
        List<Dish> dishList = myPage.getRecords();
        List<DishDto> dishDtoList = dishList.stream().map(
                item ->{
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item,dishDto);
                    Category category = categoryMapper.selectById(item.getCategoryId());
                    if(category != null){
                        dishDto.setCategoryName(category.getName());
                    }
                    return dishDto;
                }
        ).collect(Collectors.toList());
        myPage.setRecords(dishDtoList);
        log.debug("分组结果{}*******总记录数{}",myPage.getRecords(),myPage.getTotal());
        return new PageResult<>(myPage.getTotal(),myPage.getRecords());
    }

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //根据菜名查询菜品表是否存在
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getName,dishDto.getName());
        Integer count = dishMapper.selectCount(lambdaQueryWrapper);
        if(count > 0){
            throw new BusinessException("菜品["+dishDto.getName()+"]已经存在");
        }
        //保存菜品表
        dishMapper.insert(dishDto);
        //获取菜品口味集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //保存菜品口味表
        if(!CollectionUtils.isEmpty(flavors)){
            for (DishFlavor flavor : flavors){
                flavor.setDishId(dishDto.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    @Override
    public DishDto findById(Long id) {
        //定义返回DishDto
        DishDto dishDto = new DishDto();
        //根据菜品id查询菜品表
        Dish dish = dishMapper.selectById(id);
        //将dish对象数据copy到DishDto中
        BeanUtils.copyProperties(dish,dishDto);
        //根据菜品id查询菜品口味表
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavorList = dishFlavorMapper.selectList(lambdaQueryWrapper);
        dishDto.setFlavors(flavorList);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getName,dishDto.getName());
        lambdaQueryWrapper.ne(Dish::getId,dishDto.getId());
        Integer count = dishMapper.selectCount(lambdaQueryWrapper);
        if(count > 0){
            throw new BusinessException("菜品["+dishDto.getName()+"]已经存在");
        }
        //更新菜品表
        dishMapper.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorMapper.delete(dishFlavorLambdaQueryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        //保存菜品口味表
        if(!CollectionUtils.isEmpty(flavors)){
            for (DishFlavor flavor : flavors){
                flavor.setDishId(dishDto.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

//    @Override
//    public R<String> uploadStatus(Integer status, List<Long> ids) {
//        return null;
//    }

    @Override
    public R<String> uploadStatus(Integer status, List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(ids != null,Dish::getId,ids);
        queryWrapper.orderByDesc(Dish::getPrice);

        List<Dish> list = dishMapper.selectList(queryWrapper);
        for(Dish dish : list){
            if(dish != null){
                dish.setStatus(status);
                dishMapper.updateById(dish);
            }
        }
        return R.success("售卖状态修改成功");
    }




    @Override
    public List<DishDto> list(Dish dish) {
        List<DishDto> dishDtoList = null;

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1

        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return dishDtoList;
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishMapper.selectList(queryWrapper);

        dishDtoList = dishList.stream().map(item -> {
            //3.1遍历一次,就创建一个DishDto
            DishDto dto = new DishDto();
            //3.2把dish的数据拷贝到dto身上
            BeanUtils.copyProperties(item,dto);

            //3.3设置口味数据
            LambdaQueryWrapper<DishFlavor> lqy = new LambdaQueryWrapper<>();
            lqy.eq(DishFlavor::getDishId,item.getId());
            dto.setFlavors(dishFlavorMapper.selectList(lqy));
            //3.4返回dto
            return dto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return dishDtoList;
    }

    @Override
    public void deleteWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.eq(Dish::getStatus,1);
        Integer count = dishMapper.selectCount(queryWrapper);
        if(count > 0){
            //如果不能删除，则抛出一个业务异常
            throw new BusinessException("套餐正在售卖中，不能删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        dishMapper.deleteBatchIds(ids);

        Set keys = redisTemplate.keys("dish_*");

        redisTemplate.delete(keys);


        //delete from setmeal_dish where setmeal_id in (1,2,3)
        //LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        ///lambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        //删除关系表中的数据----setmeal_dish
        //dishFlavorMapper.delete(lambdaQueryWrapper);
    }


}
